package com.lazydong.apiforward.client.gui.pages.apiroute;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.lazydong.apiforward.client.framework.PageAbility;
import com.lazydong.apiforward.client.framework.PageInfo;
import com.lazydong.apiforward.client.framework.annotation.ChildPage;
import com.lazydong.apiforward.client.gui.enums.PageInfoEnum;
import com.lazydong.apiforward.client.gui.util.JarResFileCopyUtil;
import com.lazydong.apiforward.client.gui.util.RouteUpdateUtil;
import com.lazydong.gui.layout.Margin;
import com.lazydong.gui.layout.Size;
import com.lazydong.gui.layout.linear.HLinearAlign;
import com.lazydong.gui.layout.linear.LinearLayoutUtil;
import com.lazydong.gui.layout.linear.VLinearAlign;

import javax.swing.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;

@ChildPage
public class ApiRoutePage extends PageAbility<ApiRoutePageConfig> {

    private static final AtomicBoolean serverEnableStatus = new AtomicBoolean(false);

    private static final Map<String, JTextField> portFieldMap = new HashMap<>();

    @Override
    public PageInfo getPageInfoEnum() {
        return PageInfoEnum.API_ROUTE;
    }

    @Override
    public int getOrder() {
        return 1;
    }

    @Override
    public void initConfig() {
        if (!FileUtil.exist(PageInfoEnum.API_ROUTE.runDataPath())) {
            ApiRoutePageConfig config = new ApiRoutePageConfig();
            config.developers = new ArrayList<>();
            config.developers.add(new Developer());
            config.routeUrlInfos = new ArrayList<>();
            config.routeUrlInfos.add(new RouteUrlInfo());
            String string = JSONUtil.toJsonPrettyStr(config);
            FileUtil.writeString(string, PageInfoEnum.API_ROUTE.runDataPath(), StandardCharsets.UTF_8);
        }
    }

    @Override
    public ApiRoutePageConfig loadConfig() {
        String jsonStr = FileUtil.readString(PageInfoEnum.API_ROUTE.runDataPath(), StandardCharsets.UTF_8);
        return JSONUtil.toBean(jsonStr, ApiRoutePageConfig.class);
    }

    @Override
    public void buildPage(JPanel parentJPanel, ApiRoutePageConfig config) {
        System.out.println("sd");
        LinearLayoutUtil.setVLayout(parentJPanel, VLinearAlign.Left);
        ComboBoxItemListener comboBoxItemListener = new ComboBoxItemListener();
        for (RouteUrlInfo routeUrlInfo : config.routeUrlInfos) {
            addOneRoute(parentJPanel, routeUrlInfo, config.developers, comboBoxItemListener);
        }
    }

    private void addOneRoute(JPanel parentJPanel, RouteUrlInfo routeUrlInfo, List<Developer> developers,
                             ComboBoxItemListener comboBoxItemListener) {
        if (developers.isEmpty()) {
            return;
        }
        JPanel onePanel = new JPanel();
        LinearLayoutUtil.addComponent(parentJPanel, onePanel, Size.ofHeightRatio(4), Margin.ofTopRatio(1));

        LinearLayoutUtil.setHLayout(onePanel, HLinearAlign.Centre);

        JLabel serverNameLabel = new JLabel(routeUrlInfo.serverName);
        LinearLayoutUtil.addComponent(onePanel, serverNameLabel, Size.ofRatio(20, 90));

        JLabel apiPrefixLabel = new JLabel(routeUrlInfo.apiPrefix);
        LinearLayoutUtil.addComponent(onePanel, apiPrefixLabel, Size.ofRatio(20, 90));

        JComboBox<RouteComboBoxInfo> comboBox = new JComboBox<>();
        comboBox.addItemListener(comboBoxItemListener);
        RouteComboBoxInfo kongBai = new RouteComboBoxInfo();
        kongBai.setServerName(routeUrlInfo.serverName);
        kongBai.setApiPrefix(routeUrlInfo.apiPrefix);
        kongBai.setRoutePath("");
        kongBai.setDevelopIpAddr("");
        comboBox.addItem(kongBai);
        for (Developer developer : developers) {
            RouteComboBoxInfo routeComboBoxInfo = new RouteComboBoxInfo();
            routeComboBoxInfo.setServerName(routeUrlInfo.serverName);
            routeComboBoxInfo.setApiPrefix(routeUrlInfo.apiPrefix);
            routeComboBoxInfo.setRoutePath(routeUrlInfo.routePath);
            routeComboBoxInfo.setDevelopIpAddr(developer.ipAddress);
            comboBox.addItem(routeComboBoxInfo);
        }
        LinearLayoutUtil.addComponent(onePanel, comboBox, Size.ofRatio(50, 90));

        JTextField portField = new JTextField();
        portFieldMap.put(routeUrlInfo.apiPrefix, portField);
        LinearLayoutUtil.addComponent(onePanel, portField, Size.ofRatio(50, 90));
    }

    @Override
    public void afterServiceStart() {
        serverEnableStatus.set(true);
    }

    /**
     * 下拉框监听器
     */
    private static class ComboBoxItemListener implements ItemListener {
        @Override
        public void itemStateChanged(ItemEvent e) {
            if (ItemEvent.SELECTED != e.getStateChange()) {
                return;
            }
            if (!serverEnableStatus.get()) {
                // 服务还没有启动
                return;
            }
            RouteComboBoxInfo info = (RouteComboBoxInfo) e.getItem();
            if (StrUtil.isBlank(info.developIpAddr)) {
                RouteUpdateUtil.updateRoute(info.serverName, info.apiPrefix, "");
                return;
            }
            JTextField jTextField = portFieldMap.get(info.apiPrefix);
            jTextField.setEditable(StrUtil.isBlank(info.developIpAddr));
            String text = jTextField.getText();
            String routeIpAddr = info.developIpAddr + info.routePath;
            if (StrUtil.isNotBlank(text)) {
                routeIpAddr = getDevelopIp(info.developIpAddr) + ":" + text + info.routePath;
            }
            RouteUpdateUtil.updateRoute(info.serverName, info.apiPrefix, routeIpAddr);
        }
    }

    private static String getDevelopIp(String developIpAddr) {
        String[] split = developIpAddr.split(":");
        if (split.length == 3) {
            return split[0] + ":" + split[1];
        }
        return developIpAddr;
    }
}
